package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.util.DBUtil;

import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public List<Cart> listCart(Cart cart) {
        CartDao cartDao = new CartDaoImpl();
        List<Cart> list = new ArrayList<>();
        try {
            //数据库链接
            DBUtil.getConnection();
            list=cartDao.listCart(cart);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭Connection
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(Cart cart) {
        CartDao cartDao = new CartDaoImpl();
        int result=0;
        try {
            DBUtil.beginTransaction();         //开启一个事务
            //数据库链接
            DBUtil.getConnection();
            result=cartDao.saveCart(cart);
            DBUtil.commitTransaction();        //提交一个事务
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();  //回滚一个事务
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }finally {
            // 关闭Connection
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int updateCart(Cart cart) {
        CartDao cartDao = new CartDaoImpl();
        int result=0;
        try {
            //数据库链接
            DBUtil.beginTransaction();         //开启一个事务
            result=cartDao.updateCart(cart);
            DBUtil.commitTransaction();        //提交一个事务
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();  //回滚一个事务
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            // 关闭Connection
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int removeCart(Cart cart){
        CartDao cartDao = new CartDaoImpl();
        int result=0;
        try {
            //数据库链接
            DBUtil.beginTransaction();
            result=cartDao.removeCart(cart);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();  //回滚一个事务
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            // 关闭Connection
            DBUtil.close();
        }
        return result;
    }
}

